// Project name:JavaRedis
// Creator:muhong
// Date time:2022/12/8,10:10 下午
// Name:NioServerSocketChannel

package org.gmh.channel.nio;

import org.gmh.channel.ChannelFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.List;

public class NioServerSocketChannel extends AbstractNioMessageChannel {

    private final static Logger logger = LoggerFactory.getLogger(NioServerSocketChannel.class);

    public NioServerSocketChannel(SelectableChannel ch) {
        super(null, ch, SelectionKey.OP_ACCEPT);
    }

    @Override
    protected int doReadMessages(List<Object> buf) throws Exception {
        logger.info("handle a new client connection");
        SocketChannel channel = javaChannel().accept();

        if (channel != null) {
            buf.add(new NioSocketChannel(this, channel));
            return 1;
        }
        return 0;
    }

    @Override
    public ServerSocketChannel javaChannel() {
        return (ServerSocketChannel) super.javaChannel();
    }

    @Override
    public boolean isRegistered() {
        return false;
    }

    @Override
    public NioUnsafe unsafe() {
        return super.unsafe();
    }

    @Override
    public boolean isActive() {
        return isOpen() && javaChannel().socket().isBound();
    }

    @Override
    protected void doClose() throws Exception {
        super.doClose();
        javaChannel().close();
    }

    @Override
    public ChannelFuture write(Object msg) {
        return null;
    }

    @Override
    public ChannelFuture close() {
        return null;
    }
}
